<script setup lang="ts">
import { HomeWrap } from '@/components/HomeWrap'
import { ref, onMounted } from 'vue'
import CartItem from './components/CartItem.vue'
import { cartList, updateCart, deleteCart } from '@/api/cart/client'
import type { CartWithProductInfo } from '@/api/cart/types'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

defineOptions({
  name: 'Cart'
})

// 购物车商品列表
const cartItems = ref<CartWithProductInfo[]>([])

// 总金额
const totalMoney = ref(0)

// 计算总金额
const calculateTotal = () => {
  totalMoney.value = cartItems.value.reduce((total, item) => {
    return total + item.productSku.price * item.cart.qty
  }, 0)
}

// 更新商品数量
const updateItemCount = async (cartId: number, qty: number) => {
  try {
    // 更新本地数据
    const item = cartItems.value.find((item) => item.cart.cartId === cartId)
    if (item) {
      const oldQty = item.cart.qty
      item.cart.qty = qty

      // 调用接口更新购物车
      const params = {
        cartId: cartId,
        qty: qty,
        remark: ''
      }

      const res = await updateCart(params)
      if (res) {
        ElMessage.success('购物车更新成功')
        calculateTotal()
      } else {
        // 如果接口调用失败，恢复原来的数量
        item.cart.qty = oldQty
        ElMessage.error('购物车更新失败')
      }
    }
  } catch (error) {
    console.error('更新购物车失败:', error)
    ElMessage.error('更新购物车失败')
  }
}

// 删除购物车商品
const deleteCartItem = async (cartId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteCart(cartId)
    if (res) {
      // 从本地列表中移除
      const index = cartItems.value.findIndex((item) => item.cart.cartId === cartId)
      if (index !== -1) {
        cartItems.value.splice(index, 1)
        calculateTotal()
        ElMessage.success('删除成功')
      }
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除购物车商品失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取购物车列表
const fetchCartList = async () => {
  try {
    const res = await cartList({})
    if (res && res.data && res.data.list) {
      cartItems.value = res.data.list
      calculateTotal()
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error('获取购物车列表失败')
  }
}

const router = useRouter()
const jumpToCheckout = () => {
  router.push({
    name: 'UserCheckout'
  })
}

// 初始化
onMounted(() => {
  fetchCartList()
})
</script>

<template>
  <HomeWrap>
    <div class="main-wrap">
      <h2 class="page-title">购物车</h2>
      <template v-if="cartItems.length > 0">
        <CartItem
          v-for="item in cartItems"
          :key="item.cart.cartId"
          :cart-id="item.cart.cartId"
          v-model="item.cart.qty"
          :img="item.productSku.mainImg || '/images/1.webp'"
          :title="item.productSku.title"
          :origin-price="item.productSku.crossedPrice"
          :current-price="item.productSku.price"
          :specs="
            item.productSku.attrValueList
              ? item.productSku.attrValueList.map((attr) => `${attr.pnValue}:${attr.pvValue}`)
              : []
          "
          @update:modelValue="updateItemCount(item.cart.cartId, $event)"
          @delete="deleteCartItem"
        />
      </template>
      <template v-else>
        <el-empty description="购物车为空，快去添加商品吧！" />
      </template>
    </div>
    <!-- 结算吸底栏 -->
    <div class="checkout-bar">
      <div class="total">
        合计：<span class="money">￥{{ totalMoney.toFixed(2) }}</span>
      </div>
      <el-button
        type="primary"
        size="large"
        round
        @click="jumpToCheckout()"
        :disabled="cartItems.length === 0"
        >去结算</el-button
      >
    </div>
  </HomeWrap>
</template>

<style scoped>
.page-title {
  padding: 16px;
}

.checkout-bar {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.total {
  font-size: 16px;
}
.total .money {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

/* 给主体留 56px 安全区，防止内容被遮挡 */
.main-wrap {
  padding-bottom: 50px;
}
</style>
